<?php namespace App\Services\Admin\App;

use Lang;
use App\Models\Admin\App as AppModel;
use App\Models\Admin\AppEp as AppEpModel;
use App\Services\Admin\App\Validate\App as AppValidate;
use App\Services\BaseProcess;

/**
 * oauth
 *
 * @author jiang <mylampblog@163.com>
 */
class Process extends BaseProcess
{
    /**
     * app model
     * 
     * @var object
     */
    private $appModel;

    /**
     * app model
     * 
     * @var object
     */
    private $appEpModel;

    /**
     * app validate
     * 
     * @var object
     */
    private $appValidate;

    /**
     * 初始化
     *
     * @access public
     */
    public function __construct()
    {
        if( ! $this->appModel) $this->appModel = new AppModel();
        if( ! $this->appEpModel) $this->appEpModel = new AppEpModel();
        if( ! $this->appValidate) $this->appValidate = new AppValidate();
    }

    /**
     * 增加新的应用
     *
     * @param object $data
     * @access public
     * @return boolean true|false
     */
    public function addApp(\App\Services\Admin\App\Param\Save $data)
    {
        if( ! $this->appValidate->add($data)) return $this->setErrorMsg($this->appValidate->getErrorMessage());
        $redirectUri = $data['redirect_uri']; unset($data['redirect_uri']);
        $result = $this->appModel->addApp($data->toArray());
        if($result !== false) {
            $epData['client_id'] = $data['id'];
            $epData['redirect_uri'] = $redirectUri;
            $epData['created_at'] = date('Y-m-d H:i:s');
            $epData['updated_at'] = date('Y-m-d H:i:s');
            return $this->appEpModel->addAppEp($epData);
        }
        return $this->setErrorMsg(Lang::get('common.action_error'));
    }

    /**
     * 删除应用
     * 
     * @param array $ids 应用的id
     * @access public
     * @return boolean true|false
     */
    public function detele($ids)
    {
        if( ! is_array($ids)) return false;
        if($this->appModel->deleteApp($ids) !== false) return true;
        return $this->setErrorMsg(Lang::get('common.action_error'));
    }

    /**
     * 编辑应用
     *
     * @param object $data
     * @access public
     * @return boolean true|false
     */
    public function editApp(\App\Services\Admin\App\Param\Save $data, $oldid)
    {
        if( ! $this->appValidate->edit($data)) {
            return $this->setErrorMsg($this->appValidate->getErrorMessage());
        }

        $appData = $data->toArray();
        unset($appData['redirect_uri']);

        if($this->appModel->editApp($appData, $oldid) !== false) {
            $epData['redirect_uri'] = $data['redirect_uri'];
            $epData['updated_at'] = date('Y-m-d H:i:s');
            //使用$data['id']作为更新条件的原因是因为外键的存在，更新主表时会同时更新附表
            return $this->appEpModel->editAppEp($epData, $data['id']);
        }

        return $this->setErrorMsg(Lang::get('common.action_error'));
    }

}